home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: Type conversion
- Date: Tue, 30 Jan 1996 01:14:31 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9601300014.AA22125@dxmint.cern.ch>
- References: <4ejjka$2rf@news3.cts.com>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- jfitz@vmbb.cts.com (Jim Fitzgerald) writes:
-
- > Was wondering if a guru out there could tell me why the following
-
- There is no need to be a guru to answer the question. Only basic C
- understanding is needed.
-
- >code fragment for extracting an long from a buffer does not work.
- >Following the bad code, is a fragment that does work.. but is fairly
- >cheezy! )..
- >
- >This code compiles and runs but returns INCORRECT results:
- >
- >char buffer[512];
- >long node_left, node_right;
- >{
- > node_left = (long)*(buffer+4);
- > node_right= (long)*(buffer+8);
- >}
-
- What you say here is: "take the char stored at address buffer+4 and
- convert it to long". This is clearly not what you meant, so the correct
- expression is:
-
- node_left = *(long *)(buffer+4);
-
- which converts buffer+4 into a pointer to long and then retrieves the
- long value stored at that address (dereferences the pointer in C-speak).
-
- Note that this kind of code is very unsafe, because there is no guarantee
- that buffer+4 is a legal address for a long. If it isn't, the program will
- crash and burn on platforms which are sensitive to data alignment issues.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-